<?php
namespace Realisation\Zadolbali;

use Model\Parser\ParserOneInterface;
use Model\Parser\ParserException;
use Symfony\Component\DomCrawler\Crawler;
use Model\Entity\Message;

/**
 * Description of OneParser
 *
 * @author pahhan
 */
class OneParser implements ParserOneInterface
{
    public function getMessage(Crawler $crawler)
    {
        $id_el = $crawler->filter('h2 a span.number');
        if( !$id_el->count() ) {
            throw new ParserException('Cant find id by "h2 a span.number"');
        }
        $id = preg_replace('/[^\\d]/', '', $id_el->text(), -1);
        if( empty($id) ) {
            throw new ParserException('id is empty');
        }
        $message = new Message();
        $message->setExternalId($id);

        $title_el = $crawler->filter('h2 a');
        if( $title_el->count() ) {
            $t_a = explode('—  ', $title_el->text());
            if( !empty($t_a[1]) ) {
                $message->setTitle($t_a[1]);
            }
        }

        $content_el = $crawler->filter('p.the');
        if( !$content_el->count() ) {
            throw new ParserException('Cant find content by "p.the"');
        }
        $message->setContent($content_el->html());

        $date_el = $crawler->filter('p.timestamp');
        $published_at = NULL;
        if( $date_el->count() ) {
            $published_at = $this->processDate($date_el->text());
            if(  $published_at ) {
                $message->setPublishedAt($published_at);
            }
        }

        $tags_el = $crawler->filter('p.tags a');
        $tags = $tags_el->extract('_text');
        if( count($tags) ) {
            $message->setTags(implode(', ', $tags));
        }

        return $message;
    }

    protected function processDate($date)
    {
        $matches = NULL;
        $result = preg_match('/(\\d{1,2}) ([А-Яа-яЁё]+) (\\d{4}).*(\\d\\d):(\\d\\d)/u', $date, $matches);

        if( !($result && count($matches) === 6) ) return NULL;
        $month = \Util\Helper::ruMonthToNumber($matches[2]);

        $dt = new \DateTime();
        $dt->setDate($matches[3], $month, $matches[1]);
        $dt->setTime($matches[4], $matches[5], 0);

        return $dt;
    }


}

